import { ref } from 'vue'
import { useMenuStore } from '@/stores/menu'
import { useRoute, useRouter, onBeforeRouteUpdate } from 'vue-router'
import { getTabList, setTabList } from '@/composables/cookie'

export function useTagList(){
    const menuStore = useMenuStore()
    const route = useRoute() 
    const router = useRouter()

    // 当前选中的界面tab
    const activeTab = ref(route.path)

    // 导航栏 tab 数组
    const tabList = ref([
        {
            title: '仪表盘',
            path: '/admin/index'
        },
    ])

    // 处理删除标签菜单事件
    const handleCloseTab = (command) => {
        // 首页路由
        let indexPath = '/admin/index'

        // 处理关闭其他
        if (command == 'closeOthers') {
            // 过滤首页和当前页
            tabList.value = tabList.value.filter((tab) => tab.path == indexPath || tab.path == activeTab.value)
        } else if (command == 'closeAll') {
            // 切回首页
            activeTab.value = indexPath
            // 只保留首页
            tabList.value = tabList.value.filter((tab) => tab.path == indexPath)
            // 切换标签界面
            tabChange(activeTab.value)
        }
        setTabList(tabList.value)
    }

    // 移除 tab
    const removeTab = (path) => {
        let tabs = tabList.value
        let actTab = activeTab.value 

        // 如果删除当前这个 tab 需要判断删除后跳转的 tab , 否则取上一个
        if(actTab == path){
            // 循环 tabList
            tabs.forEach((tab, index) => {
                if(tab.path == path){
                    let nextTab = tabs[index + 1] || tabs[index - 1]
                    if(nextTab) {
                        actTab = nextTab.path
                    } 
                }
            })
        }

        // 激活对应的 tab
        activeTab.value = actTab

        // 过滤删除的 tab
        tabList.value = tabList.value.filter((tab) => tab.path != path)

        // 存储到 cookie 中间
        setTabList(tabList.value)

        // 切换标签界面
        tabChange(activeTab.value)
    }

    // 点击 tab 跳转界面
    const tabChange = (path) => {
        // 激活对应的 tab
        activeTab.value = path
        // 路由跳转
        router.push(path)
    }

    // 添加 tab 标签
    function addTab(tab){
        //标签是否存在
        let isTabNotExisted = tabList.value.findIndex(item => item.path == tab.path) == -1
        // 如果不存在
        if(isTabNotExisted) {
            // 添加标签
            tabList.value.push(tab)
        }
        //存储 tabList 到 cookie 中
        setTabList(tabList.value)
    }

    onBeforeRouteUpdate((to, from) => {
        //设置被激活的tab
        activeTab.value = to.path
        // 添加 tab 标签
        addTab({
            title: to.meta.title,
            path: to.path
        })
    })

    // 初始化 tab 表单方法
    function initTabList(){
        let tabs = getTabList()
        if (tabs) {
            tabList.value = tabs
        }
    }
    //初始化 tab
    initTabList()

    return {
        menuStore,
        activeTab,
        tabList,
        tabChange,
        removeTab,
        handleCloseTab
    }
}